//
//  ViewController.m
//  UIwhere
//
//  Created by mac on 15-12-24.
//  Copyright (c) 2015年 yb. All rights reserved.
//

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface ViewController ()<UIWebViewDelegate,UITextFieldDelegate>
{
    UIWebView *web;
    UIActivityIndicatorView *av;
    UITextField *text;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    web = [[UIWebView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:web];
    web.delegate =self;
    
    av = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [av sizeToFit];
    av.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
    [self.view addSubview:av];
    
    text = [[UITextField alloc]initWithFrame:CGRectMake(15, 0, self.view.frame.size.width - 30, 44)];
    text.layer.borderWidth = 2;
    text.keyboardType = UIKeyboardTypeURL;
    text.delegate = self;
    [self.navigationController.navigationBar addSubview:text];
    
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [web loadRequest:request];
    self.navigationController.toolbarHidden = NO;
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithTitle:@"后退" style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
    UIBarButtonItem *gfor = [[UIBarButtonItem alloc]initWithTitle:@"前进" style:UIBarButtonItemStylePlain target:self action:@selector(goFor:)];
    UIBarButtonItem *refresh = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(gorefresh:)];

    self.toolbarItems = @[back,gfor,refresh];
}

- (void)goBack:(id)sender
{
    if ([web canGoBack]) {
        [web goBack];
    }
}

- (void)goFor:(id)sender
{
    if ([web canGoForward]) {
        [web canGoForward];
    }
}

- (void)gorefresh:(id)sender
{
    [web reload];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [av startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [av stopAnimating];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [av stopAnimating];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *urlstr = textField.text;
    if (![urlstr hasPrefix:@"http://"]) {
        urlstr = [@"http://" stringByAppendingString:urlstr];
    }
    NSURL *url = [NSURL URLWithString:urlstr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    [web loadRequest:request];
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
